package com.apimanage.gateway.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 网关路由配置类
 * 配置API请求的路由规则
 */
@Configuration
public class GatewayRouteConfig {

    /**
     * 配置路由规则
     */
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                // API服务路由
                .route("api-service-route", r -> r
                        .path("/api/service/**")
                        .filters(f -> f
                                .stripPrefix(1)
                                .rewritePath("/service/(?<segment>.*)", "/\\$\\{segment}")
                        )
                        .uri("lb://api-service")
                )
                // 认证服务路由 - 使用直接URL而不是负载均衡
                .route("auth-center-route-alt", r -> r
                        .path("/api/auth-center/**")
                        .filters(f -> f
                                .stripPrefix(2)
                                // 添加响应头用于调试
                                .addResponseHeader("X-Route-ID", "auth-center-route")
                                // 注册和登录接口已在用户中心配置为允许匿名访问，无需添加认证头
                        )
                        .uri("http://localhost:8081") // 直接指向auth-center的HTTP端口
                )
                // 用户服务路由
                .route("user-center-route", r -> r
                        .path("/api/user-center/**")
                        .filters(f -> f
                                .stripPrefix(2)
                                // 添加响应头用于调试
                                .addResponseHeader("X-Route-ID", "user-center-route")
                                // 注册和登录接口已在用户中心配置为允许匿名访问，无需添加认证头
                        )
                        .uri("lb://user-center")
                )
                // 监控服务路由
                .route("monitor-service-route", r -> r
                        .path("/api/monitor/**")
                        .filters(f -> f
                                .stripPrefix(1)
                                .rewritePath("/monitor/(?<segment>.*)", "/\\$\\{segment}")
                        )
                        .uri("lb://monitor-service")
                )
                .build();
    }

}